// EchoServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

using namespace CO::SpiFoundation::RoomFW;
using namespace std;

int main(int argc, char* argv[])
{
	//cout << endl;
	//for (int i = 0; i < argc; ++i)
	//	cout << argv[i] << endl;

	DynamicBindingManager::Instance();  // Make it destruct after PortRouter.  TODO:  Handle in RoomFW!!!

	std::string logFile = (argc > 1) ? argv[1] : "ECHO_SERVER";
	logFile += ".log";
	G_LOGGER.setFile(true, logFile.c_str());
	G_LOGGER.setVerbosity(CO::SpiFoundation::RoomFW::LV_ALL);
	if (!G_LOGGER.start())
	{
		cout << "Failed to start port router.  Enter any character to exit..." << endl;
		char c;
		cin >> c;
	}

	WSADATA WSAData;
	if (SOCKET_ERROR == ::WSAStartup(WORD MAKEWORD(2, 2), &WSAData))
	{
		SHOW_SOCKET_ERROR(false, "EchoServer", "::WSAStartup");
		cout << "Failed to initialize sockets.  Enter any character to exit..." << endl;
		char c;
		cin >> c;
	} 

	if (!PortRouter::Instance().start((argc > 2) ? ::atoi(argv[2]) : 27001, (argc > 3) ? argv[3] : "127.0.0.1"))
	{
		cout << "Failed to start port router.  Enter any character to exit..." << endl;
		char c;
		cin >> c;
	}

	IEchoServerSP server = IEchoServer::Create((argc > 1) ? argv[1] : "ECHO_SERVER");
	if (server->start())
	{
		SimpleEvent stopEvent;
		VERIFY(stopEvent.create(false, false, "ECHO_SERVER_STOP_EVENT"));
		stopEvent.wait();
		server->stop();
	}
	else
	{
		cout << "Failed to start server.  Enter any character to exit..." << endl;
		char c;
		cin >> c;
	}
	PortRouter::Instance().stop();
	SHOW_SOCKET_ERROR((SOCKET_ERROR != WSACleanup()), "EchoServer", "::WSACleanup");
	return 0;
}

